package com.css.dzj.dzjap.modules.info.service.impl;

import com.css.dzj.dzjap.common.util.Constant;
import com.css.dzj.dzjap.common.util.R;
import com.css.dzj.dzjap.common.util.ServiceUtil;
import com.css.dzj.dzjap.common.util.userinfo.UserInfoService;
import com.css.dzj.dzjap.modules.apunit.entity.ApUnitEntity;
import com.css.dzj.dzjap.modules.apunit.entity.QApUnitEntity;
import com.css.dzj.dzjap.modules.construnit.entity.ConstructionUnitEntity;
import com.css.dzj.dzjap.modules.construnit.entity.QConstructionUnitEntity;
import com.css.dzj.dzjap.modules.enterprise.service.EnterpriseService;
import com.css.dzj.dzjap.modules.info.mapper.EvalUnitMapper;
import com.css.dzj.dzjap.modules.info.mapper.ExpertMapper;
import com.css.dzj.dzjap.modules.info.service.ConstrService;
import com.css.dzj.dzjap.modules.info.service.EvalUnitService;
import com.css.dzj.dzjap.modules.info.vo.ApJsVo;
import com.css.dzj.dzjap.sys.user.entity.LoginUser;
import com.querydsl.core.QueryResults;
import com.querydsl.core.types.ExpressionUtils;
import com.querydsl.core.types.Predicate;
import com.querydsl.core.types.Projections;
import com.querydsl.core.types.dsl.ComparableExpressionBase;
import com.querydsl.core.types.dsl.NumberExpression;
import com.querydsl.jpa.impl.JPAQueryFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class EvalUnitServiceImpl implements EvalUnitService {
    @Autowired
    EvalUnitMapper evalUnitMapper;
    @Autowired
    ServiceUtil serviceUtil;
    @Autowired
    private JPAQueryFactory jpaQueryFactory;
    @Autowired
    EnterpriseService enterpriseService;
    @Autowired
    private ConstrService constrService;
    @Override
    public QueryResults<ApUnitEntity> getPage(Pageable pageRequest, String unitName, String uniscid,
                                              String startTime, String endTime, String spStatus, String spPerson, String sbStatus, HttpServletRequest request) {
       // List idNum=enterpriseService.idHbNumber();
        QApUnitEntity q=QApUnitEntity.apUnitEntity;
        Predicate predicate=q.isNotNull().or(q.isNull());
        predicate = (unitName == null || unitName.isEmpty()) ? predicate : ExpressionUtils.and(predicate, q.unitName.like("%" + unitName + "%"));
        predicate = (uniscid == null || uniscid.isEmpty()) ? predicate : ExpressionUtils.and(predicate, q.uniscid.like("%" + uniscid + "%"));
        predicate=(spStatus==null || spStatus.isEmpty())?predicate:ExpressionUtils.and(predicate,q.spStatus.eq(spStatus));
        predicate=(spPerson==null || spPerson.isEmpty())? predicate : ExpressionUtils.and(predicate,q.createPerson.like("%"+spPerson+"%"));
        predicate=(sbStatus==null || sbStatus.isEmpty())?predicate:ExpressionUtils.and(predicate,q.sbStatus.eq(sbStatus));
        if((StringUtils.isEmpty(startTime))&&(!StringUtils.isEmpty(endTime))){
            Date endDate=null;
            SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
            try {
                endDate = sf.parse(endTime + " "+"23:59:59.999");
            } catch (ParseException e) {
                e.printStackTrace();
            }
            predicate =ExpressionUtils.and(predicate, q.spTime.loe(endDate));
        }
        if((!StringUtils.isEmpty(startTime))&&(StringUtils.isEmpty(endTime))){
            Date startDate = null;
            SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
            try {
                startDate = sf.parse(startTime+" "+"00:00:00.000");
            } catch (ParseException e) {
                e.printStackTrace();
            }
            predicate =ExpressionUtils.and(predicate, q.spTime.goe(startDate));
        }
        if((!StringUtils.isEmpty(startTime))&&(!StringUtils.isEmpty(endTime))){
            Date startDate = null;
            Date endDate=null;
            SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
            try {
                startDate = sf.parse(startTime+" "+"00:00:00.000");
                endDate = sf.parse(endTime+" "+"23:59:59.999");
            } catch (ParseException e) {
                e.printStackTrace();
            }
            predicate =ExpressionUtils.and(predicate, q.spTime.between(startDate,endDate));
        }

        /**
         * 获取suser
         */
        R r = serviceUtil.getUserInfoByRequest(request);
        String suserName = "";
        String location = "";
        String address="";
        String userUnit ="";
        if(r.getCode().equals("200")){
            LoginUser userInfo =  (LoginUser)r.get("data");
            /**
             * 获取用户名
             */
            suserName =userInfo.getLoginName();
            /**
             * 获取用户的省份
             */
            String orgName = userInfo.getOrgName();
            //location = orgName.substring(0,orgName.indexOf("地震局"));
            location = orgName.replace("地震局","");
            address = userInfo.getAddress();
            userUnit= userInfo.getOrgName();
        }
        if(!"".equals(location) && null!=location){

           if(location.contains("安评单位")){
               String idCard= findApIdCard(suserName);
               if(!StringUtils.isEmpty(idCard)) {
                   predicate = ExpressionUtils.and(predicate, q.uniscid.eq(idCard));
               }
               return jpaQueryFactory.selectFrom(q).where(predicate, q.delFlag.eq(Constant.NO_DELETE)).orderBy(q.createTime.desc()).offset(pageRequest.getOffset()).limit(pageRequest.getPageSize()).fetchResults();
           }else if(location.equals(Constant.LOCATIONZG)) {
                return jpaQueryFactory.selectFrom(q).where(predicate, q.delFlag.eq(Constant.NO_DELETE),q.sbStatus.eq(Constant.EXCPRES_STATE_Yes)).orderBy(q.createTime.desc()).offset(pageRequest.getOffset()).limit(pageRequest.getPageSize()).fetchResults();
           }else{
                predicate=ExpressionUtils.and(predicate,q.registAddr.like("%"+location+"%").or(q.createPerson.eq(suserName)));
                return jpaQueryFactory.selectFrom(q).where(predicate, q.delFlag.eq(Constant.NO_DELETE)).orderBy(q.createTime.desc()).offset(pageRequest.getOffset()).limit(pageRequest.getPageSize()).fetchResults();
           }
        }else {
            throw new  RuntimeException("用户信息不存在");
        }
    }

    @Override
    public boolean delEval(String id) {
        evalUnitMapper.deleteById(id);
        return true;
    }

    @Override
    public QueryResults<ApUnitEntity> getPageEval(Pageable pageable, String enterpriseName, String enterpriseIdNumber) {
        List idNum=enterpriseService.idHbNumber();
        QApUnitEntity q=QApUnitEntity.apUnitEntity;
        Predicate predicate=q.isNotNull().or(q.isNull());
        predicate = (enterpriseName == null || enterpriseName.isEmpty()) ? predicate : ExpressionUtils.and(predicate, q.unitName.like("%" + enterpriseName + "%"));
        predicate = (enterpriseIdNumber == null || enterpriseIdNumber.isEmpty()) ? predicate : ExpressionUtils.and(predicate, q.uniscid.like("%" + enterpriseIdNumber + "%"));
        return jpaQueryFactory.selectFrom(q).where(predicate,q.delFlag.eq(Constant.NO_DELETE),q.uniscid.notIn(idNum)).orderBy(q.createTime.desc()).offset(pageable.getOffset()).limit(pageable.getPageSize()).fetchResults();
    }

    @Override
    @Transactional
    public void update(ApUnitEntity apUnitEntity) {

    }

    @Override
    public ApUnitEntity findById(String id) {
        ApUnitEntity apUnitEntity=evalUnitMapper.findById(id).get();
        return apUnitEntity;
    }

    @Override
    public String findApIdCard(String userName) {
        QApUnitEntity q=QApUnitEntity.apUnitEntity;

        return jpaQueryFactory.select(q.uniscid).from(q).where(q.userName.eq(userName),q.delFlag.eq(Constant.NO_DELETE)).fetchOne();
    }

    @Override
    public HashMap getCount() {
        QApUnitEntity q=QApUnitEntity.apUnitEntity;
        List<ApUnitEntity> list=jpaQueryFactory.selectFrom(q).where(q.delFlag.eq(Constant.NO_DELETE)).fetch();
        List idNum=enterpriseService.idPJNumber();
        HashMap map=new HashMap();
        for (ApUnitEntity apUnitEntity:list) {
            String address=apUnitEntity.getRegistAddr();
            String[] arr=address.split("-");
            String arry=null;
            if(arr[0].contains("市")){
                arry =arr[0].replace("市","");
            }else if(arr[0].contains("省")){
                arry = arr[0].replace("省","");
            }
            Long count=jpaQueryFactory.select(q.registAddr.count()).from(q).
                    where(q.delFlag.eq(Constant.NO_DELETE),q.registAddr.eq(address),
                            q.id.eq(apUnitEntity.getId()),q.sbStatus.eq(Constant.EXCPRES_STATE_Yes),q.uniscid.in(idNum)).fetchOne();
            Long value=(Long)map.get(arry);
            if(value==null) {
                if(count!=0){
                    map.put(arry, count);
                }
            }else {
                value=count.longValue()+value.longValue();
                map.put(arry,value);
            }
        }
        return map;
    }

    @Override
    public HashMap getCountByYear(String year) {
        QApUnitEntity q=QApUnitEntity.apUnitEntity;
        Predicate predicate=q.isNotNull().or(q.isNull());
        List<ApUnitEntity> list=jpaQueryFactory.selectFrom(q).where(q.delFlag.eq(Constant.NO_DELETE)).fetch();
        List idNum=enterpriseService.idPJNumber();
        HashMap map=new HashMap();
        for (ApUnitEntity apUnitEntity:list) {
            String address=apUnitEntity.getRegistAddr();
            String[] arr=address.split("-");
            ComparableExpressionBase<?> creatYear = q.spTime.year();
            predicate =ExpressionUtils.and(predicate,((NumberExpression) creatYear).stringValue().eq(year)) ;
            Long count=jpaQueryFactory.select(q.registAddr.count()).from(q).
                    where(q.delFlag.eq(Constant.NO_DELETE),q.registAddr.eq(address),
                            q.id.eq(apUnitEntity.getId()),q.sbStatus.eq(Constant.EXCPRES_STATE_Yes),q.uniscid.in(idNum),predicate).fetchOne();
            Long value=(Long)map.get(arr[0]);
            if(value==null) {
                if(count!=0) {
                    map.put(arr[0], count);
                }
            }else {
                value=count.longValue()+value.longValue();
                map.put(arr[0],value);
            }

        }
        return map;
    }

    @Override
    public QueryResults<ApUnitEntity> getPage(Pageable pageRequest, String unitName, String uniscid, String startTime, String endTime, String spStatus, String spPerson, String sbStatus) {
        QApUnitEntity q=QApUnitEntity.apUnitEntity;
        Predicate predicate=q.isNotNull().or(q.isNull());
        predicate = (unitName == null || unitName.isEmpty()) ? predicate : ExpressionUtils.and(predicate, q.unitName.like("%" + unitName + "%"));
        predicate = (uniscid == null || uniscid.isEmpty()) ? predicate : ExpressionUtils.and(predicate, q.uniscid.like("%" + uniscid + "%"));
        predicate=(spStatus==null || spStatus.isEmpty())?predicate:ExpressionUtils.and(predicate,q.spStatus.eq(spStatus));
        predicate=(spPerson==null || spPerson.isEmpty())? predicate : ExpressionUtils.and(predicate,q.createPerson.like("%"+spPerson+"%"));
        predicate=(sbStatus==null || sbStatus.isEmpty())?predicate:ExpressionUtils.and(predicate,q.sbStatus.eq(sbStatus));
        if((StringUtils.isEmpty(startTime))&&(!StringUtils.isEmpty(endTime))){
            Date endDate=null;
            SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
            try {
                endDate = sf.parse(endTime + " "+"23:59:59.999");
            } catch (ParseException e) {
                e.printStackTrace();
            }
            predicate =ExpressionUtils.and(predicate, q.spTime.loe(endDate));
        }
        if((!StringUtils.isEmpty(startTime))&&(StringUtils.isEmpty(endTime))){
            Date startDate = null;
            SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
            try {
                startDate = sf.parse(startTime+" "+"00:00:00.000");
            } catch (ParseException e) {
                e.printStackTrace();
            }
            predicate =ExpressionUtils.and(predicate, q.spTime.goe(startDate));
        }
        if((!StringUtils.isEmpty(startTime))&&(!StringUtils.isEmpty(endTime))){
            Date startDate = null;
            Date endDate=null;
            SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
            try {
                startDate = sf.parse(startTime+" "+"00:00:00.000");
                endDate = sf.parse(endTime+" "+"23:59:59.999");
            } catch (ParseException e) {
                e.printStackTrace();
            }
            predicate =ExpressionUtils.and(predicate, q.spTime.between(startDate,endDate));
        }
        return jpaQueryFactory.selectFrom(q)
                .where(predicate, q.delFlag.eq(Constant.NO_DELETE))
                .orderBy(q.createTime.desc())
                .offset(pageRequest.getOffset())
                .limit(pageRequest.getPageSize())
                .fetchResults();
    }

    @Override
    public List<ApUnitEntity> queryByParams(String unitName, String uniscid, String startTime, String endTime, String spStatus, String spPerson, String sbStatus) {
        QApUnitEntity q=QApUnitEntity.apUnitEntity;
        Predicate predicate=q.isNotNull().or(q.isNull());
        predicate = (unitName == null || unitName.isEmpty()) ? predicate : ExpressionUtils.and(predicate, q.unitName.like("%" + unitName + "%"));
        predicate = (uniscid == null || uniscid.isEmpty()) ? predicate : ExpressionUtils.and(predicate, q.uniscid.like("%" + uniscid + "%"));
        predicate=(spStatus==null || spStatus.isEmpty())?predicate:ExpressionUtils.and(predicate,q.spStatus.eq(spStatus));
        predicate=(spPerson==null || spPerson.isEmpty())? predicate : ExpressionUtils.and(predicate,q.createPerson.like("%"+spPerson+"%"));
        predicate=(sbStatus==null || sbStatus.isEmpty())?predicate:ExpressionUtils.and(predicate,q.sbStatus.eq(sbStatus));
        if((StringUtils.isEmpty(startTime))&&(!StringUtils.isEmpty(endTime))){
            Date endDate=null;
            SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
            try {
                endDate = sf.parse(endTime + " "+"23:59:59.999");
            } catch (ParseException e) {
                e.printStackTrace();
            }
            predicate =ExpressionUtils.and(predicate, q.spTime.loe(endDate));
        }
        if((!StringUtils.isEmpty(startTime))&&(StringUtils.isEmpty(endTime))){
            Date startDate = null;
            SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
            try {
                startDate = sf.parse(startTime+" "+"00:00:00.000");
            } catch (ParseException e) {
                e.printStackTrace();
            }
            predicate =ExpressionUtils.and(predicate, q.spTime.goe(startDate));
        }
        if((!StringUtils.isEmpty(startTime))&&(!StringUtils.isEmpty(endTime))){
            Date startDate = null;
            Date endDate=null;
            SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
            try {
                startDate = sf.parse(startTime+" "+"00:00:00.000");
                endDate = sf.parse(endTime+" "+"23:59:59.999");
            } catch (ParseException e) {
                e.printStackTrace();
            }
            predicate =ExpressionUtils.and(predicate, q.spTime.between(startDate,endDate));
        }
        return jpaQueryFactory.selectFrom(q)
                .where(predicate, q.delFlag.eq(Constant.NO_DELETE))
                .orderBy(q.createTime.desc())
                .fetch();
    }

    @Override
    public List<ApUnitEntity> queryByIds(String ids) {
        List<String> idList = Arrays.asList(ids.split(","));
        List<ApUnitEntity> list = evalUnitMapper.findAllById(idList);
        return list;
    }

    @Override
    public Integer getTotalCount() {
        QApUnitEntity q=QApUnitEntity.apUnitEntity;
        return (int)jpaQueryFactory.selectFrom(q).where(q.delFlag.eq(Constant.NO_DELETE)).fetchCount();
    }

   /* @Override
    public  List<ApUnitEntity> getPageLH( String unitName, String uniscid) {
        //安评单位
        QApUnitEntity q=QApUnitEntity.apUnitEntity;
        //建设单位
        QConstructionUnitEntity  cEnty =QConstructionUnitEntity.constructionUnitEntity;
        Predicate predicate=q.isNotNull().or(q.isNull());
        predicate = (unitName == null || unitName.isEmpty()) ? predicate : ExpressionUtils.and(predicate, q.unitName.like("%" + unitName + "%"));
        predicate = (uniscid == null || uniscid.isEmpty()) ? predicate : ExpressionUtils.and(predicate, q.uniscid.like("%" + uniscid + "%"));
        predicate = ExpressionUtils.and(predicate,q.delFlag.eq(Constant.NO_DELETE));
        List<ApUnitEntity> list = jpaQueryFactory.selectFrom(q)
                               .where(predicate)
                               .fetch();
        return list;
    }
*/
   /* @Override
    @Transactional
    public QueryResults<ApUnitEntity> getPageLHCx(  Pageable pageRequest,String unitName, String uniscid,Integer pageSize, Integer pageNo) {

        try {
            List<ApUnitEntity> wlist = getPageLH(unitName,uniscid);
            List<ApUnitEntity> alist = new ArrayList<>();
            if (wlist != null && wlist.size() > 0) {
                int currIdx = (pageNo > 1 ? (pageNo - 1) * pageSize : 0);
                for (int i = 0; i < pageSize && i < wlist.size() - currIdx; i++) {
                    ApUnitEntity data = wlist.get(currIdx + i);
                    alist.add(data);
                }
            }
            List<ConstructionUnitEntity>  clist = constrService.getPageLH(unitName,uniscid);
            if(null!=clist && clist.size()>0){
                for(ConstructionUnitEntity cEntity : clist){
                    ApUnitEntity apJsVo = new ApUnitEntity();
                    apJsVo.setUnitName(cEntity.getEntName());
                    apJsVo.setUniscid(cEntity.getUniscid());
                    apJsVo.setUnitRegistTime(cEntity.getEstablishTime());
                    apJsVo.setLegalMan(cEntity.getLegalPerson());
                    alist.add(apJsVo);
                }
            }
            //将数据按照注册时间降序排
            if(null != alist && alist.size()>0){
                List<ApUnitEntity> proEntityList = new ArrayList<>();
                for(ApUnitEntity cpList : alist ){
                    if (null!=cpList.getUnitRegistTime()){
                        proEntityList.add(cpList);
                    }
                }
                if(null != proEntityList && proEntityList.size()>0){
                    List<ApUnitEntity> pEList = proEntityList.stream().sorted(Comparator.comparing(ApUnitEntity::getUnitRegistTime).reversed()).collect(Collectors.toList());
                    QueryResults<ApUnitEntity> rwsQueryResults = new QueryResults(pEList, (long)pageRequest.getPageSize(), pageRequest.getOffset(), wlist.size());
                    return rwsQueryResults;
                }
            }
            QueryResults<ApUnitEntity> rwsQueryResults = new QueryResults(alist, (long)pageRequest.getPageSize(), pageRequest.getOffset(), wlist.size());
            return rwsQueryResults;
        }catch (Exception e){
             e.printStackTrace();
            throw  new RuntimeException(e.getMessage());
        }
    }
*/

}
